package o2o.service.shop;

import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.JYMathDoubleUtils;
import com.jinyou.utils.common.ObjectUtils;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import com.jinyouapp.common.utils.map.AMapModel;
import com.jinyouapp.common.utils.map.AMapUtils;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.shop.*;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.user.UserInfoMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.shop.*;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.area.RegionInfoVO;
import o2o.dao.VO.shop.*;
import o2o.service.delivery.DeliveryOrderSyncService;
import o2o.service.delivery.to.DeliveryShopTO;
import o2o.company.model.ShopInfo;
import o2o.system.data.SHOP_MANAGE_TYPE_FREE_OR_AGENT;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.task.image.ImageService;
import o2o.web.actions.agent.CityAgentMan;
import o2o.web.actions.shop.ShopMan;
import o2o.web.actions.shop.ShopTipMan;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺
 */
public class ShopService {

    private ShopService() {
    }

    private static ShopService instance = null;

    public static ShopService getInstance() {
        if (instance == null) {
            synchronized (ShopService.class) {
                if (instance == null) {
                    instance = new ShopService();
                }
            }
        }
        return instance;
    }


    /**
     * @param sysAppKey
     * @param info
     * @desc 注册哒哒门店
     */
    public boolean registerOrUpdateDeliverShop(String sysAppKey, ShopInfo info, boolean isRegisterAutoEvent) {
        if (SYS_SETTINGS.IS_OTHER_POST == 2 && info != null) {
            System.out.println("门店注册--->" + info.getId());
            if (StringUtils.isEmpty(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }
            DeliveryShopTO to = new DeliveryShopTO();
            to.setShopId(info.getId()).setSysCustomer(sysAppKey)
                    .setProv(info.getProvince())
                    .setCity(info.getCity())
                    .setCounty(info.getCounty())
                    .setAddress(info.getAddress())
                    .setName(info.getShopName())
                    .setLat(info.getLat())
                    .setLng(info.getLng())
                    .setResponserPhone(info.getTelephone())
                    .setResponser(info.getShopName());
            try {
                if (StringUtils.isEmpty(to.getProv()) || StringUtils.isEmpty(to.getCity()) || StringUtils.isEmpty(to.getCounty())) {
                    AMapModel aMapModel = AMapUtils.getAddressByLngAndLat(info.getLat(), info.getLng());
                    if (aMapModel != null) {
                        if (StringUtils.isEmpty(to.getProv())) {
                            to.setProv(aMapModel.getProvince());
                        }
                        if (StringUtils.isEmpty(to.getCity())) {
                            to.setCity(aMapModel.getCity());
                        }
                        if (StringUtils.isEmpty(to.getCounty())) {
                            to.setCounty(aMapModel.getCounty());
                        }
                    }
                }
                DeliveryOrderSyncService.getInstance().addOrUpdateDeliverShop(DeliveryOrderSyncService.DELIVERY_PLATEFORM_DADA, to);
                modifyShopInfoRegister(sysAppKey, info, 1);
            } catch (Exception e) {
                e.printStackTrace();
                modifyShopInfoRegister(sysAppKey, info, 0);
                // 创建一个事件
                createEvent(sysAppKey, info.getId(), isRegisterAutoEvent);
                return false;
            }
            return true;
        }
        return false;
    }

    //    修改状态 判断是否修改成功
    private void modifyShopInfoRegister(String sysAppKey, ShopInfo info, int state) {
        if (info.getRegisterShopState() == 0 || info.getRegisterShopState() == -1) {
            if (state != 1) {
                state = -1;
            }
        } else if (info.getRegisterShopState() == -2 || info.getRegisterShopState() == 1) {
            if (state != 1) {
                state = -2;
            }
        }
        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(PojoTables.ShopInfo)
                .append(" set registerShopState = ").append(state)
                .append(" where delFlag = 0 and id =").append(info.getId());
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
            ShopMemory.getInstance().modifyById(info.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(info.getId());
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
    }

    // 创建 事件 让其自动发送
    private void createEvent(String sysAppKey, Long shopId, boolean isRegisterAutoEvent) {
        if (isRegisterAutoEvent) {

        }
    }


    // 根据id 获取店铺
    public ShopInfo getById(String sysAppKey, Long shopId) {
        return ShopMemory.getInstance().getShopById(shopId);
    }


    //
    public ShopInfo getShopByUsername(String sysAppKey, String username) {
        return ShopMemory.getInstance().getShopByUsername(username);
    }

    //
    //获取某一店铺的详细信息
    public ShopInfoAndGameVO getShopInfoAndGameDetailOne(UserInfo user, ShopInfo info) {
        try {
            if (null == info) {
                return null;
            }
            List<ShopTypeInfoVO> typeInfoVOList = new ArrayList<ShopTypeInfoVO>();

            //获取店铺所属行业
            List<Integer> list = ShopTypeRelationMemory.getInstance().shopTypeList(info.getId());
            if (ValidateUtil.isAbsList(list)) {
                for (int i = 0; i < list.size(); i++) {
                    if (null == list.get(i)) {
                        continue;
                    }


                }
            }


            ShopInfoAndGameVO infoVO = convertSimplicityShopGameVo(info);
            infoVO.setShopId(info.getId());
//            // 店铺背景图
//            if (ValidateUtil.isNotNull(infoVO.getImageUrlB()) && ValidateUtil.isNotNetUrl(infoVO.getImageUrlB())) {
////                infoVO.setImageUrlB(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImageUrlB());
//                infoVO.setImageUrlB(ImageService.getImgUrl(info.getImgUpVer()) + infoVO.getImageUrlB());
//            }
//            if (ValidateUtil.isNotNull(infoVO.getRecomImageUrl()) && ValidateUtil.isNotNetUrl(infoVO.getRecomImageUrl())) {
//                infoVO.setRecomImageUrl(ImageService.getImgUrl(info.getImgUpVer()) + infoVO.getRecomImageUrl());
//            }
//            //add by qilonghe 2020.7.21 start
//            // 店铺头像大图
//            if (ValidateUtil.isNotNull(infoVO.getImageUrlBig()) && ValidateUtil.isNotNetUrl(infoVO.getImageUrlBig())) {
////                infoVO.setImageUrlB(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImageUrlB());
//                infoVO.setImageUrlBig(ImageService.getImgUrl(info.getImgUpVer()) + infoVO.getImageUrlBig());
//            }
            //add by qilonghe 2020.7.21 end


            //评论信息
            if (null != info.getCommentInfo()) {
                ShopCommentInfoVO commentInfoVO = new ShopCommentInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(info.getCommentInfo(), commentInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (ValidateUtil.isNotNull(commentInfoVO.getSignPhoto()) && ValidateUtil.isNotNetUrl(commentInfoVO.getSignPhoto())) {
                    commentInfoVO.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + commentInfoVO.getSignPhoto());
                }
                if (ValidateUtil.isNotNull(commentInfoVO.getImage1Url()) && ValidateUtil.isNotNetUrl(commentInfoVO.getImage1Url())) {
                    commentInfoVO.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + commentInfoVO.getImage1Url());
                }
                if (ValidateUtil.isNotNull(commentInfoVO.getImage2Url()) && ValidateUtil.isNotNetUrl(commentInfoVO.getImage2Url())) {
                    commentInfoVO.setImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + commentInfoVO.getImage2Url());
                }
                if (ValidateUtil.isNotNull(commentInfoVO.getImage3Url()) && ValidateUtil.isNotNetUrl(commentInfoVO.getImage3Url())) {
                    commentInfoVO.setImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + commentInfoVO.getImage3Url());
                }
                if (ValidateUtil.isNotNull(commentInfoVO.getImage4Url()) && ValidateUtil.isNotNetUrl(commentInfoVO.getImage4Url())) {
                    commentInfoVO.setImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + commentInfoVO.getImage4Url());
                }
                infoVO.setCommentInfos(commentInfoVO);
            }

            //店铺所属行业
            infoVO.setShopType(typeInfoVOList);

            //登录用户判断是否收藏过
            if (user != null && ShopLikeMemory.getInstance().isLike(user.getUsername(), infoVO.getId())) {//登录用户判断是否收藏
                infoVO.setIsLike(1);
            }

            //获取店铺实景
            List<ShopImageTypeVO> images = ShopMan.getShopImages(info.getId());
            if (ValidateUtil.isAbsList(images)) {
                infoVO.setShopImages(images);
            }

            //获取店铺所属行业
            List<RegionInfoVO> relationList = ShopMan.getRegionListOfShop(infoVO.getId());
            if (ValidateUtil.isAbsList(relationList)) {
                infoVO.setRegions(relationList);
            }

            //获取店铺评分、星级、销量
            ShopInfoExtra extraInfo = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(info.getId());
            if (null != extraInfo) {
                infoVO.setStar(extraInfo.getStar());
                infoVO.setScore(extraInfo.getScore());
                infoVO.setOrderCounts(extraInfo.getOrderCounts());
                infoVO.setMonthOrderCount(extraInfo.getMonthOrderCount());
                infoVO.setShowOrderCounts(extraInfo.getShowOrderCounts());
                infoVO.setTotalCommentCount(ValidateUtil.isAbsInteger(extraInfo.getTotalCommentCount()) ? extraInfo.getTotalCommentCount() : 0);
                infoVO.setShopCategoryApplyState(extraInfo.getShopCategoryApplyState());
            }


            //获取店铺服务的商圈列表
            List<Long> agentList = ShopAgentRelationMemory.getInstance().agentListOfShopId(info.getId());
            if (ValidateUtil.isAbsList(agentList)) {
                List<CityAgentVO> agentVOList = new ArrayList<>();
                for (int i = 0; i < agentList.size(); i++) {
                    Long agentId = agentList.get(i);
                    if (ValidateUtil.isNotID(agentId)) {
                        continue;
                    }
                    CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
                    if (null == cityAgent) {
                        continue;
                    }
                    CityAgentVO cityAgentVO = new CityAgentVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(cityAgent, cityAgentVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (null == infoVO.getCityAgent()) {
                        infoVO.setCityAgent(cityAgentVO);
                    }
                    agentVOList.add(cityAgentVO);
                }
                infoVO.setCityAgentList(agentVOList);
                // 设置第一个为店铺商圈信息
                if (agentVOList.size() > 0) {
                    infoVO.setCityAgent(agentVOList.get(0));
                    if (ValidateUtil.isNotID(infoVO.getAgentId()) && infoVO.getCityAgent() != null) {
                        infoVO.setAgentId(infoVO.getCityAgent().getId());
                    }
                }
            }

            //店铺需要实时更新位置
            if (null != SYS_SETTINGS.SHOP_NOW_POSITION_NEED && 0 == 1 - SYS_SETTINGS.SHOP_NOW_POSITION_NEED) {
                ShopPositionInfo shopPositionInfo = ShopPositionMemory.getInstance().get(info.getId());
                if (null != shopPositionInfo) {
                    infoVO.setLat(shopPositionInfo.getLat());
                    infoVO.setLng(shopPositionInfo.getLng());
                    infoVO.setAddress(shopPositionInfo.getAddress());
                    infoVO.setCity(shopPositionInfo.getCity());
                    infoVO.setProvince(shopPositionInfo.getProvince());
                }
            }

            //店铺标签
            List<ShopTip> tipList = ShopTipMan.tipListOfShopId(info.getId());
            if (ValidateUtil.isAbsList(tipList)) {
                infoVO.setShopTipList(tipList);
            }

            // 店主信息
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(info.getOwnUsername());
            infoVO.setOwnUserInfo(userInfo);

            // 额外信息
            ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(info.getId());
            if (null != shopInfoExtra) {
                ShopInfoExtraVO extraVO = new ShopInfoExtraVO();
                ObjectUtils.copyPropertiesExclude(shopInfoExtra, extraVO);
                infoVO.setExtraVO(extraVO);
            }
            infoVO.setShopBanners(ShopBannerService.getInstance().findShopBannerList(infoVO.getId(), null));
            return infoVO;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public ShopInfoAndGameVO getShop(UserInfo user, ShopInfo info) {
        ShopInfoAndGameVO shopInfoVO = convertSimplicityShopGameVo(info);
        if (null == shopInfoVO) {
            return null;
        }
        //登录用户判断是否收藏过
        if (user != null && ShopLikeMemory.getInstance().isLike(user.getUsername(), shopInfoVO.getId())) {//登录用户判断是否收藏
            shopInfoVO.setIsLike(1);
            // 是不是 购买过过
            boolean b = OrderInfoMemory.getInstance().hasOrderInShopId(user.getUsername(), shopInfoVO.getId());
            if (b) {
                shopInfoVO.setIsOftenBrowse(1);
            }
        }
        //获取店铺评分、星级、销量
        ShopInfoExtra extraInfo = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopInfoVO.getId());
        if (null != extraInfo) {
            shopInfoVO.setStar(extraInfo.getStar());
            shopInfoVO.setScore(JYMathDoubleUtils.round(extraInfo.getScore(), 1));
            shopInfoVO.setOrderCounts(extraInfo.getOrderCounts());
            shopInfoVO.setMonthOrderCount(extraInfo.getMonthOrderCount());
            shopInfoVO.setShowOrderCounts(extraInfo.getShowOrderCounts());
            shopInfoVO.setShopTag(extraInfo.getShopTag());
        }
        return shopInfoVO;
    }

    //获取店铺的简单信息
    public ShopInfoVO getShopInfoVoDetailOne(UserInfo user, ShopInfo info) {
        if (info == null) {
            return null;
        }
        ShopInfoVO shopInfoVO = new ShopInfoVO();
        BeanUtils.copyProperties(info, shopInfoVO);
        if (null == shopInfoVO) {
            return null;
        }
        //登录用户判断是否收藏过
        if (user != null && ShopLikeMemory.getInstance().isLike(user.getUsername(), shopInfoVO.getId())) {//登录用户判断是否收藏
            shopInfoVO.setIsLike(1);
        }
        if (ValidateUtil.isNotNetUrl(info.getImageUrlB()) && ValidateUtil.isNotNetUrl(info.getImageUrlB())) {
//            shopInfoVO.setImageUrlB(SYS_CONFIG_PATH.IMAGE_BASE_URL + shopInfoVO.getImageUrlB());
            shopInfoVO.setImageUrlB(ImageService.getImgUrl(info.getImgUpVer()) + shopInfoVO.getImageUrlB());
        }
        if (ValidateUtil.isNotNull(shopInfoVO.getImageUrl()) && ValidateUtil.isNotNetUrl(shopInfoVO.getImageUrl())) {
            String thumb = ImageService.getThumbnailImgUrl(shopInfoVO.getImageUrl(), shopInfoVO.getImgUpVer(), shopInfoVO.getThumbnailState());
            shopInfoVO.setImageThumbnailUrl(thumb);
            shopInfoVO.setImageUrl(ImageService.getImgUrl(shopInfoVO.getImgUpVer()) + shopInfoVO.getImageUrl());
        }
        if (ValidateUtil.isNotNull(shopInfoVO.getRecomImageUrl()) && ValidateUtil.isNotNetUrl(shopInfoVO.getRecomImageUrl())) {
            shopInfoVO.setRecomImageUrl(ImageService.getImgUrl(shopInfoVO.getImgUpVer()) + shopInfoVO.getRecomImageUrl());
        }
        //获取店铺评分、星级、销量
        ShopInfoExtra extraInfo = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopInfoVO.getId());
        if (null != extraInfo) {
            shopInfoVO.setStar(extraInfo.getStar());
            shopInfoVO.setScore(extraInfo.getScore());
            shopInfoVO.setOrderCounts(extraInfo.getOrderCounts());
            shopInfoVO.setMonthOrderCount(extraInfo.getMonthOrderCount());
            shopInfoVO.setShowOrderCounts(extraInfo.getShowOrderCounts());
        }

        return shopInfoVO;
    }

    public ShopInfoAndGameVO convertSimplicityShopGameVo(ShopInfo info) {
        ShopInfoAndGameVO vo = new ShopInfoAndGameVO();
        BeanUtils.copyProperties(info, vo);
        // 店铺背景图
        if (ValidateUtil.isNotNull(vo.getImageUrlB()) && ValidateUtil.isNotNetUrl(vo.getImageUrlB())) {
//                infoVO.setImageUrlB(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImageUrlB());
            vo.setImageUrlB(ImageService.getImgUrl(info.getImgUpVer()) + vo.getImageUrlB());
        }
        if (ValidateUtil.isNotNull(vo.getRecomImageUrl()) && ValidateUtil.isNotNetUrl(vo.getRecomImageUrl())) {
            vo.setRecomImageUrl(ImageService.getImgUrl(info.getImgUpVer()) + vo.getRecomImageUrl());
        }
        //add by qilonghe 2020.7.21 start
        // 店铺头像大图
        if (ValidateUtil.isNotNull(vo.getImageUrlBig()) && ValidateUtil.isNotNetUrl(vo.getImageUrlBig())) {
//                infoVO.setImageUrlB(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImageUrlB());
            vo.setImageUrlBig(ImageService.getImgUrl(info.getImgUpVer()) + vo.getImageUrlBig());
        }
        return vo;
    }


    public ShopInfoVO getShopInfoById(Long shopId) {
        if (ValidateUtil.isNotID(shopId)) {
            return null;
        }
        ShopInfo shopInfo = this.getById(null, shopId);
        if (shopInfo == null) {
            return null;
        }
        return this.getShopInfoVoDetailOne(null, shopInfo);
    }


    // 店铺申请成为云商家
    public void shopApplyCloudShop(String sysAppKey, ShopInfo info, String opUser) throws Exception {
        if (info == null) {
            throw new Exception("店铺信息不能为空....");
        }
        if ((info.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_PROVIDE) > 0) {
            throw new Exception("您已经是云商家提供商");
        }
        ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(info.getId());
        if (shopInfoExtra == null) {
            throw new Exception("店铺其他信息为空");
        }
        if (shopInfoExtra.getCloudShopApplyState() == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_ING) {
            // 申请中
            throw new Exception("申请中,请耐心等待");
        } else if (shopInfoExtra.getCloudShopApplyState() == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_PASS) {
            // 申请通过De
            // 修改
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.ShopInfo)
                    .append(" set updateUser ='").append(opUser).append("'")
                    .append(" ,cloudShopType = 3")
                    .append(" where id = ").append(info.getId()).append(" and delFlag = 0");
            UserDaoSql.getInstance().executeBySql(sql.toString());
            ShopMemory.getInstance().modifyById(info.getId());
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(info.getId());
            JmsSender.setTopicSender(notify);
        } else {
            // 未申请的 或  申请被拒的
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.SHOP_INFO_EXTRA)
                    .append(" set updateUser ='").append(opUser).append("'")
                    .append(" ,cloudShopApplyState = 1")
                    .append(" where shopId = ").append(info.getId()).append(" and delFlag = 0");
            UserDaoSql.getInstance().executeBySql(sql.toString());
            ShopExtraInfoMemory.getInstance().addOrModify(info.getId());
        }
    }

    // 审核成为云商家的申请
    public void passOrNoCloudShopApply(String sysAppKey, Long shopId, int cloudShopApplyState, String opUser) throws Exception {
        ShopInfo shop = ShopMemory.getInstance().getShopById(shopId);
        if (shop == null) {
            throw new Exception("未获取到商家信息");
        }
        if ((shop.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_PROVIDE) > 0) {
            throw new Exception("当前状态下不可操作");
        }
        ShopInfoExtra extraInfo = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopId);
        if (extraInfo == null) {
            throw new Exception("未获取到商家其他信息");
        }
        if (extraInfo.getCloudShopApplyState() != CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_ING) {
            throw new Exception("当前状态不可操作");
        }
        if (cloudShopApplyState == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_NO_PASS) {
            StringBuffer sql = new StringBuffer();
            sql.append(" update").append(PojoTables.SHOP_INFO_EXTRA)
                    .append(" set updateUser ='").append(opUser).append("'")
                    .append(", cloudShopApplyState = ").append(cloudShopApplyState)
                    .append(" where id = ").append(extraInfo.getId());
            UserDaoSql.getInstance().executeBySql(sql.toString());
            ShopExtraInfoMemory.getInstance().addOrModify(shopId);
        } else if (cloudShopApplyState == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_PASS) {
            Connection conn = null;
            try {
                conn = UserDaoSql.getInstance().getConnection();
                conn.setAutoCommit(false);
                StringBuffer sql = new StringBuffer();
                sql.append(" update ").append(PojoTables.SHOP_INFO_EXTRA)
                        .append(" set updateUser ='").append(opUser).append("'")
                        .append(", cloudShopApplyState = ").append(cloudShopApplyState)
                        .append(" where id = ").append(extraInfo.getId());
                UserDaoSql.getInstance().executeBySql(sql.toString(), conn);
                //
                StringBuffer sql2 = new StringBuffer();
                sql2.append(" update ").append(PojoTables.ShopInfo)
                        .append(" set updateUser ='").append(opUser).append("'")
                        .append(", cloudShopType = 3")
                        .append(" where id = ").append(shopId);
                UserDaoSql.getInstance().executeBySql(sql2.toString(), conn);
                conn.commit();
                ShopExtraInfoMemory.getInstance().addOrModify(shopId);
                ShopMemory.getInstance().modifyById(shopId);

                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                throw e;
            } finally {
                UserDaoSql.getInstance().close(conn);
            }
        } else {
            throw new Exception("未知的操作状态");
        }
    }


    // 获取周围商家信息
    public List<ShopInfo> getAroundShopInfoList(String city, Double lat, Double lng, Long agentId, Integer shopCategory, Integer isWork) {
        List<ShopInfo> list = null;
        if (ValidateUtil.isID(agentId)) {
            list = ShopMan.listOfAgentId(agentId, null, null, null, null, null, null);
        } else {
            if (ValidateUtil.isLatLng(lat, lng)) {
                //精确商圈方式
                if (null != SYS_SETTINGS.SHOP_MANAGE_TYPE && 0 == SHOP_MANAGE_TYPE_FREE_OR_AGENT.AGENT - SYS_SETTINGS.SHOP_MANAGE_TYPE) {
                    //单商圈还是多商圈同时返回
                    if (null != SYS_SETTINGS.LOCAL_CITY_AGENT_TYPE && 0 == SYS_SETTINGS.LOCAL_CITY_AGENT_TYPE) {     // 定位时城市按下商圈列表还是单独商圈  1单独商圈，0商圈列表
                        //商圈列表
                        List<CityAgentVO> agentList = CityAgentMan.getCityAgentList(city, lat, lng);
                        if (ValidateUtil.isAbsList(agentList)) {
                            list = new ArrayList<>();
                            for (int i = 0; i < agentList.size(); i++) {
                                CityAgentVO agentVO = agentList.get(i);
                                if (agentVO != null) {
                                    List<Long> tmpList = ShopAgentRelationMemory.getInstance().listOfAgentId(agentVO.getId());
                                    if (!ValidateUtil.isAbsList(tmpList)) {
                                        continue;
                                    }
                                    for (Long shopId : tmpList) {
                                        ShopInfo shop = ShopMemory.getInstance().getShopById(shopId);
                                        if (shop != null) {
                                            list.add(shop);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        //单独商圈
                        CityAgentVO cityAgentVO = CityAgentMan.getCityAgent(city, lat, lng);
                        if (null == cityAgentVO) {
                        } else {
                            List<Long> shopIds = ShopAgentRelationMemory.getInstance().listOfAgentId(cityAgentVO.getId());
                            if (ValidateUtil.isAbsList(shopIds)) {
                                for (Long shopId : shopIds) {
                                    ShopInfo shop = ShopMemory.getInstance().getShopById(shopId);
                                    if (shop != null) {
                                        list.add(shop);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                list = ShopMemory.getInstance().list(false, null,
                        city, "", "",
                        null,
                        false, false, false, false);//该城市店铺列表  管理后台可能用到

            }
        }
        if (ValidateUtil.isAbsList(list)) {
            return list.stream().filter(item -> {
                if (shopCategory != null && (item.getShopCategory() == null || (item.getShopCategory() & shopCategory) <= 0)) {
                    return false;
                }
                if (isWork != null && item.getIsWork() - isWork != 0) {
                    return false;
                }
                return true;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * > 5. 申请成为团购商家 (shop_info_extra)[update by yangtk]
     * > [user](shop_info_extra)
     * <p>
     * ALTER TABLE `shop_info_extra`
     * ADD COLUMN `shopCategoryApplyState`  INT (4)  DEFAULT '0' COMMENT '团购商家申请状态 0 未申请 1 申请中  10 申请通过 -10 申请被拒' AFTER `cloudShopApplyState`;
     *
     * @param info
     * @param shopCategory
     * @param opUser
     * @throws Exception
     */
    // 申请成为团购商家
    public void shopApplyShopCategory(ShopInfo info, int shopCategory, String opUser) throws Exception {
        if ((info.getShopCategory() & shopCategory) > shopCategory) {
            throw new Exception("您已经是团购上商家,无需重复申请");
        }
        ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(info.getId());
        if (shopInfoExtra == null) {
            throw new Exception("店铺其他信息为空");
        }
        if (shopInfoExtra.getShopCategoryApplyState() == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_ING) {
            // 申请中
            throw new Exception("申请中,请耐心等待");
        } else if (shopInfoExtra.getShopCategoryApplyState() == CLOUD_SHOP_APPLY_STATE.CLOUD_SHOP_APPLY_PASS) {
            // 申请通过De
            // 修改
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.ShopInfo)
                    .append(" set updateUser ='").append(opUser).append("'")
                    .append(" ,shopCategory = (shopCategory|").append(shopCategory).append(")")
                    .append(" where id = ").append(info.getId()).append(" and delFlag = 0");
            UserDaoSql.getInstance().executeBySql(sql.toString());
            ShopMemory.getInstance().modifyById(info.getId());
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(info.getId());
            JmsSender.setTopicSender(notify);
        } else {
            ShopVerify shopVerify = findVerifyShopOrCreate(info, opUser);
            shopVerify.setShopCategory(shopCategory);
            Connection conn = null;
            try {
                conn = UserDaoSql.getInstance().getConnection();
                conn.setAutoCommit(false);
                // 未申请的 或  申请被拒的
                StringBuffer sql = new StringBuffer();
                sql.append("update ").append(PojoTables.SHOP_INFO_EXTRA)
                        .append(" set updateUser ='").append(opUser).append("'")
                        .append(" ,shopCategoryApplyState = 1")
                        .append(" where shopId = ").append(info.getId()).append(" and delFlag = 0");
                UserDaoSql.getInstance().executeBySql(sql.toString(), conn);
                UserDaoSql.getInstance().saveObj(PojoTables.ShopVerify, shopVerify, conn);
                conn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                throw e;
            } finally {
                UserDaoSql.getInstance().close(conn);
            }
            ShopExtraInfoMemory.getInstance().addOrModify(info.getId());
        }
    }


    private ShopVerify findVerifyShopOrCreate(ShopInfo shopInfo, String opUser) {
        ShopVerify shopVerify = findVerifyShopByOwnUsername(shopInfo.getOwnUsername());
        if (shopVerify == null) {
            shopVerify = new ShopVerify();
            BeanUtils.copyProperties(shopInfo, shopVerify);
            shopVerify.setOwnUsername(shopInfo.getOwnUsername());
            shopVerify.setImageUrl3(shopInfo.getImageUrl());
        }
        shopVerify.setCreateTime(DateUtils.getCurrTime());
        shopVerify.setId(null);
        shopVerify.setIsVerify(0);
        shopVerify.setCreateUser(opUser);
        shopVerify.setRefuseReason(null);
        shopVerify.setDelFlag(0);
        shopVerify.setCloseDate(null);
        shopVerify.setOrderCounts(null);
        shopVerify.setVerifyStatus(ShopVerify.ING);
        return shopVerify;
    }

    // 查询一个对应的verify
    private ShopVerify findVerifyShopByOwnUsername(String ownUsername) {
        StringBuilder sql = new StringBuilder();
        sql.append(" select * from ").append(PojoTables.ShopVerify)
                .append(" where delFlag = 0 and  ownUsername = '").append(ownUsername).append("' ")
                .append(" and  verifyStatus = ").append(ShopVerify.OVER).append(" limit 0,1");
        ShopVerify shopVerify = null;
        try {
            shopVerify = (ShopVerify) UserDaoSql.getInstance().getObject(ShopVerify.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return shopVerify;
    }


}
